﻿// <copyright>
// Copyright (c) 2008 - 2009, Microsoft, All Rights Reserved
// </copyright>
//
// Licensed under the Microsoft Public License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at 
//
// http://www.opensource.org/licenses/ms-pl.html

namespace LiveLabs.Logging.Logs
{
    using System;
    using System.IO;

    /// <summary>
    /// Implementation of <see cref="Log"/> that writes to a file.
    /// </summary>
    public class FileLog : TextWriterLog
    {
        /// <summary>
        /// Initializes a new instance of the FileLog class.
        /// </summary>
        /// <param name="filePath">The path to the file to log to</param>
        /// <remarks>Appends to the file at <paramref name="filePath"/></remarks>
        public FileLog(string filePath)
            : this(filePath, true)
        {
        }

        /// <summary>
        /// Initializes a new instance of the FileLog class.
        /// </summary>
        /// <param name="filePath">The path to the file to log to</param>
        /// <param name="append">True if you want to append to the file, false to truncate</param>
        public FileLog(string filePath, bool append)
            : this(new FileInfo(filePath), append)
        {
        }

        /// <summary>
        /// Initializes a new instance of the FileLog class.
        /// </summary>
        /// <param name="info">The <see cref="System.IO.FileInfo"/> of the file to log to</param>
        /// <remarks>Appends to the file identified by <paramref name="fi"/>.</remarks>
        public FileLog(FileInfo info)
            : this(info, true)
        {
        }

        /// <summary>
        /// Initializes a new instance of the FileLog class.
        /// </summary>
        /// <param name="info">The <see cref="System.IO.FileInfo"/> of the file to log to</param>
        /// <param name="append">True if you want to append to the file, false to truncate</param>
        public FileLog(FileInfo info, bool append)
            : base(CreateWriter(info, append), TextWriterResponsibility.Owns)
        {
        }

        private static TextWriter CreateWriter(FileInfo info, bool append)
        {
            FileStream result = null;
            if (append)
            {
                result = info.Open(FileMode.Append, FileAccess.Write, FileShare.Read);
            }
            else
            {
                if (info.Exists)
                {
                    result = info.Open(FileMode.Truncate, FileAccess.Write, FileShare.Read);
                }
                else
                {
                    result = info.Open(FileMode.CreateNew, FileAccess.Write, FileShare.Read);
                }
            }

            return new StreamWriter(result);
        }
    }
}
